package com.songlanyun.modules.order.controller.api;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.getui.push.v2.sdk.core.client.DefaultApiClient;
import com.jxhh.ApiClient;
import com.songlanyun.common.annotation.RepeatSubmit;
import com.songlanyun.common.enums.GoodsConstant;
import com.songlanyun.common.enums.HouniaoConstant;
import com.songlanyun.common.enums.OrderConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.kqUtils.HttpUtil;
import com.songlanyun.common.kqUtils.Sign;
import com.songlanyun.common.utils.HouniaoApiUtil;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;
import com.songlanyun.common.utils.custom.MathUtils;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.common.validator.group.AppGroup;
import com.songlanyun.modules.account.controller.common.AbstractApiController;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.entity.UserVerifiedEntity;
import com.songlanyun.modules.account.model.dto.UserVerifiedDTO;
import com.songlanyun.modules.account.service.UserVerifiedService;
import com.songlanyun.modules.account.service.impl.UserVerifiedServiceImpl;
import com.songlanyun.modules.config.model.PointGradeConfigDTO;
import com.songlanyun.modules.config.service.PointGradeConfigService;
import com.songlanyun.modules.gains.service.ShopOrderGainsService;
import com.songlanyun.modules.goods.entity.Goods;
import com.songlanyun.modules.goods.service.GoodsService;
import com.songlanyun.modules.openSwitch.domain.YxtSwitch;
import com.songlanyun.modules.openSwitch.mapper.YxtSwitchMapper;
import com.songlanyun.modules.openSwitch.service.IYxtSwitchService;
import com.songlanyun.modules.order.entity.ChildOrder;
import com.songlanyun.modules.order.entity.Order;
import com.songlanyun.modules.order.entity.OrderReceipt;
import com.songlanyun.modules.order.model.dto.HouniaoCheckDTO;
import com.songlanyun.modules.order.model.dto.SubmitOrderDTO;
import com.songlanyun.modules.order.model.dto.SubmitOrderReceiptDTO;
import com.songlanyun.modules.order.model.dto.UpdateOrderReceiptDTO;
import com.songlanyun.modules.order.model.vo.SubmitOrderVo;
import com.songlanyun.modules.order.model.vo.UserOrderNumStatisticsVo;
import com.songlanyun.modules.order.service.ChildOrderService;
import com.songlanyun.modules.order.service.CreateOrderService;
import com.songlanyun.modules.order.service.OrderOperationService;
import com.songlanyun.modules.order.service.OrderService;
import com.songlanyun.modules.payorder.entity.PayOrder;
import com.songlanyun.modules.payorder.service.PayOrderService;
import com.songlanyun.modules.rabbitmq.mq.producer.SendOrderOrRightsOrderMsgService;
import com.songlanyun.modules.saleconfig.entity.SaleConfig;
import com.songlanyun.modules.saleconfig.service.SaleConfigService;
import com.songlanyun.modules.ship.entity.OrderPackage;
import com.songlanyun.modules.user.exception.UserException;
import com.songlanyun.modules.useraddress.entity.UserAddress;
import com.songlanyun.modules.useraddress.service.UserAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

//import org.apache.shiro.authz.annotation.RequiresPermissions;


/**
 * 销售系统中的主订单
 *
 * @author lubo
 * @email sunlightcs@gmail.com
 * @date 2020-11-16 14:14:42
 */
@Slf4j
@RestController
@RequestMapping("api/order")
public class OrderApiController extends AbstractApiController {

    // 保税产品标识
    private static Boolean ISBAOSHUI = false;

    @Resource(name = "createOrderService")
    private CreateOrderService createOrderService;
    @Autowired
    private OrderOperationService orderOperationService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private SendOrderOrRightsOrderMsgService sendOrderOrRightsOrderMsgService;

    @Autowired
    private SaleConfigService saleConfigService;

    @Value("${pay.mode.balance.enabled}")
    private boolean payModeBalanceEnabled;

    @Autowired
    private HouniaoApiUtil houniaoApiUtil;

    @Autowired
    private UserVerifiedService userVerifiedService;

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private ChildOrderService childOrderService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private YxtSwitchMapper yxtSwitchMapper;

    @Autowired
    private UserVerifiedServiceImpl userVerifiedServiceImpl;
    @Autowired
    private ShopOrderGainsService shopOrderGainsService;

    @Autowired
    private PointGradeConfigService pointGradeConfigService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("order:saleorder:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = orderService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 会员查看订单详情
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("order:saleorder:info")
    public R info(@PathVariable("id") Long id) {
        Order order = orderService.loadByUserKey(getUserId(true), id);
        if (order == null) {
            return R.ok().put("data", order);
        }
        List<ChildOrder> childOrderList = order.getChildOrderList(true);
        order.loadShop();
        switch (order.getOrderType()) {
            case SALE_ORDER:
                switch (order.getShipmentMode()) {
                    case PICK_UP:
                        order.loadOrderSelfTake();
                        break;
                    case EXPRESS:
                        order.loadOrderReceipt();
                        break;
                    default:
                        break;
                }
                break;
            case SERVICE_ORDER:
                childOrderList.forEach(o -> {
                    o.loadServiceCard().loadServiceItems();
                });
                order.loadServiceOrderContacts();
                break;
            default:
        }

        if (OrderConstant.ShipStatus.ALREADY_SHIP.equals(order.getShipStatus())) {
            OrderPackage orderPackage = order.loadOrderPackage();
            if (orderPackage != null) {
                orderPackage.loadPickup();
                orderPackage.loadExpress();
            }

        }

        return R.ok().put("data", order);
    }

    /**
     * 构建下单页数据
     */
    @PostMapping("/build")
    //@RequiresPermissions("order:saleorder:save")
    public R buildSubmitOrder(@RequestBody SubmitOrderDTO dto) {
        Boolean isBuy = false;
        if(isBuy) {
            throw new RRException("大家好，由于系统功能需升级，现在进行升级维护，如有不便敬请谅解!系统升级成功再另行通知，竭诚为您服务!");
        }

        if (userAddressService.getDefaultByUserId(getUserId(true)) == null){
            throw new RRException("请先添加收货地址");
        }

        dto.setChanelType(getClient().equals("applet") ? 1 : 2);
        dto.setUserId(getUserId(true));
        SubmitOrderVo vo = createOrderService.buildSubmitOrder(getUserId(true), dto);
        return R.ok().put("data", vo);
    }


    /**
     * 会员下单服务
     */
    @RepeatSubmit(value = "5")
    @PostMapping("/create")
    //@RequiresPermissions("order:saleorder:save")
    public R createOrder(@RequestBody SubmitOrderDTO dto) {

        Boolean isBuy = false;
        if(isBuy) {
            throw new RRException("大家好，由于系统功能需升级，现在进行升级维护，如有不便敬请谅解!系统升级成功再另行通知，竭诚为您服务!");
        }
/**
 * 如果数据中有实名信息
 */
        if (dto.getRealName() != null && !dto.getRealName().isEmpty()) {
            /**
             * 校验实名信息
             */
            if (!userVerifiedServiceImpl.verificationNameAndIdCard(dto.getRealName(), dto.getIdNo())) {
                throw new RRException(UserException.USER_VERIFIED);
            }
        }

        dto.setChanelType(getClient().equals("applet") ? 1 : 2);
        dto.setUserId(getUserId(true));
        PayOrder pay = createOrderService.createPayOrder(getUserId(true), dto);

        if (pay.getPaymentStatus().equals(OrderConstant.PaymentStatus.SUCCESS)) {
            sendOrderOrRightsOrderMsgService.paySuccessSendMsg(pay);
        } else {
            //下单成功发送消息
            sendOrderOrRightsOrderMsgService.createPayOrderSuccessSendMsg(pay);
        }
        return R.ok().put("data", pay);
    }

    /**
     * 取消支付
     */
    @RepeatSubmit(value = "5")
    @PostMapping("/cancel-pay/{payOrderId}")
    //@RequiresPermissions("order:saleorder:save")
    public R cancelPay(@PathVariable("payOrderId") Long payOrderId) {
        PayOrder payOrder = orderOperationService.cancelPay(getUserId(true), payOrderId);
        return R.ok().put("data", payOrder);
    }


    @Autowired
    private IYxtSwitchService yxtSwitchService;
    /**
     * 兑换券支付
     */
    @RepeatSubmit(value = "5")
    @PostMapping("/voucher-pay/{payOrderId}")
    //@RequiresPermissions("order:saleorder:save")
    public R voucherPay(@PathVariable("payOrderId") Long payOrderId) {
            log.info("兑换券支付==="+ payOrderId);
            YxtSwitch yxtSwitch = yxtSwitchService.selectYxtSwitchById(1L);
            PayOrder payOrder = orderOperationService.voucherPay(getUserId(true), payOrderId);
            Integer thisSwitch;
            if(payOrder.getPayMode().getCode().equals(0)){
                thisSwitch = yxtSwitch.getExBalanceSwitch();
            }else if(payOrder.getPayMode().getCode().equals(1)){
                thisSwitch = yxtSwitch.getExWechatSwitch();
            }else if(payOrder.getPayMode().getCode().equals(2)){
                thisSwitch = yxtSwitch.getExAlipaySwitch();
            }else{
                thisSwitch = 1;
            }

            if (thisSwitch == 0){
                throw new RRException("当前支付方式暂时关闭");
            }
            sendOrderOrRightsOrderMsgService.paySuccessSendMsg(payOrder);
            return R.ok().put("data", payOrder);
    }

    /**
     * 余额支付
     */
    @RepeatSubmit(value = "5")
    @PostMapping("/balance-pay/{payOrderId}")
    //@RequiresPermissions("order:saleorder:save")
    public R balancePay(@PathVariable("payOrderId") Long payOrderId) {
        YxtSwitch yxtSwitch = yxtSwitchService.selectYxtSwitchById(1L);
//        Integer balanceSwitch = yxtSwitchMapper.selectYxtSwitchById(1L).getBalanceSwitch();
//        if (balanceSwitch == 0) {
//            throw new RRException("余额支付暂不支持，请选择其他支付方式！");
//        }
        PayOrder payOrders = payOrderService.getById(payOrderId);
        ChildOrder childOrder = childOrderService.getOne(new LambdaQueryWrapper<ChildOrder>().eq(ChildOrder::getUserId, payOrders.getUserId()).orderByDesc(ChildOrder::getId)
                .last("LIMIT 1"));
        if (childOrder.getGoodsCategoryId() == (long)GoodsConstant.AreaFeature.EXCHANGING.getCode()){
            if (yxtSwitch.getExBalanceSwitch() == 0) {
                throw new RRException("余额支付暂不支持，请选择其他支付方式！");
            }
            log.info("余额支付==="+ payOrderId);
            PayOrder payOrder = orderOperationService.balancePay(getUserId(true), payOrderId);
            sendOrderOrRightsOrderMsgService.paySuccessSendMsg(payOrder);
            return R.ok().put("data", payOrder);
        }
        if (payOrderService.getById(payOrderId).getAreaFeature() == GoodsConstant.AreaFeature.ACTIVATING && yxtSwitch.getHxBalanceSwitch() == 1){
            log.info("余额支付==="+ payOrderId);
            PayOrder payOrder = orderOperationService.balancePay(getUserId(true), payOrderId);
            sendOrderOrRightsOrderMsgService.paySuccessSendMsg(payOrder);
            return R.ok().put("data", payOrder);
        }else {
            throw new RRException("余额支付暂不支持，请选择其他支付方式！");
        }
//        log.info("余额支付==="+ payOrderId);
//        PayOrder payOrder = orderOperationService.balancePay(getUserId(true), payOrderId);
//        sendOrderOrRightsOrderMsgService.paySuccessSendMsg(payOrder);
//        return R.ok().put("data", payOrder);
    }


    /**
     * 对普通订单修改收货地址
     */
    @RepeatSubmit(value = "5")
    @PutMapping("/update-receipt/{orderId}/{userAddressId}")
    public R updateReceipt(@PathVariable("orderId") Long orderId, @PathVariable("userAddressId") Long userAddressId) {
        OrderReceipt orderReceipt = orderOperationService.updateReceipt(getUserId(true), orderId, userAddressId);
        return R.ok().put("data", orderReceipt);
    }

    /**
     * 对支付订单修改收货地址
     */
    @RepeatSubmit(value = "5")
    @PutMapping("/update-receipt-payorder/{payOrderId}/{userAddressId}")
    public R updateReceiptForPayOrder(@PathVariable("payOrderId") Long payOrderId, @PathVariable("userAddressId") Long userAddressId) {
        orderOperationService.updateReceiptForPayOrder(getUserId(true), payOrderId, userAddressId);
        return R.ok();
    }


    /**
     * 会员分页查看其它交易状态订单
     *
     * @param params
     * @return
     */
    @RequestMapping("/page")
    public R userOrderPage(@RequestParam Map<String, Object> params) {
        Long userId = getUserId(false);
        Integer orderType = MapUtil.getInt(params, "order_type");
        orderType = orderType == null ? 1 : orderType;
        params.put("order_type", orderType);

        Integer areaFeature = MapUtil.getInt(params, "area_feature");
        areaFeature = areaFeature == null ? 0 : areaFeature;
        params.put("area_feature", areaFeature);

        params.put("client",getClient());
        PageUtils page = orderService.userOrdersPage(userId, params);
        return R.ok().put("page", page);
    }

    /**
     * 修改收货地址
     * @param dto
     * @return
     */
    @PutMapping("/update-receipt")
    public R updateOrderReceipt(@RequestBody UpdateOrderReceiptDTO dto){
        orderService.userOrderReceipt(getUserId(true),dto);
        return R.ok();
    }

    /**
     * 普通订单统计
     * @return
     */
    @GetMapping("general-order-count")
    public R loadGeneralOrderStatistics() {
        Long userId = getUserId(true);
        UserOrderNumStatisticsVo userOrderNumStatisticsVo = orderService.loadGeneralOrderStatistics(userId);
        return R.ok().put("data", userOrderNumStatisticsVo);
    }

    /**
     * 服务订单统计1
     * @return
     */
    @GetMapping("service-order-count")
    public R userOrderPage() {
        Long userId = getUserId(true);
        UserOrderNumStatisticsVo userOrderNumStatisticsVo = orderService.loadServiceOrderStatistics(userId);
        return R.ok().put("data", userOrderNumStatisticsVo);
    }

    /**
     * 申购订单统计
     * @return
     */
    @GetMapping("apply-order-count")
    public R loadApplyOrderStatistics() {
        Long userId = getUserId(true);
        UserOrderNumStatisticsVo userOrderNumStatisticsVo = orderService.loadApplyOrderStatistics(userId);
        return R.ok().put("data", userOrderNumStatisticsVo);
    }



    /**
     * 权益统计
     * @return
     */
    @GetMapping("/equity")
    public R loadEquityStatistics() {
        Long userId = getUserId(true);
        BigDecimal userPayConsumption = orderService.loadEquityStatistics(userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userPayConsumption",userPayConsumption);
        BigDecimal platformMonthEquity = orderService.loadPlatformMonthEquity();
        SaleConfig config = saleConfigService.getConfig();
        platformMonthEquity = MathUtils.setScaleDown(platformMonthEquity.doubleValue()*config.getEquityPercentage().doubleValue()/100 + config.getEquityTrimValue().doubleValue());
        map.put("platformMonthEquity",platformMonthEquity);
        return R.ok().put("data", map);
    }

    /**
     * 候鸟支付测试
     */
    @GetMapping("/houniao/test")
    public R houniaoTest() {
        return orderService.houniaoTest();
    }


    @GetMapping("/buy")
    public R addss() {
        JSONObject req = new JSONObject();
        req.put("source_order_no","24022215504829011067"); // 一致的单号
        req.put("username","宿浩");
        req.put("user_phone","18624459250");
        req.put("id_card","210905200103040010");
        req.put("area_id","210112");
        req.put("user_address","悦玺大厦B座16-24");
        req.put("is_pay",1);
        req.put("customs_platform_code","21013609P6"); // 不变 公司备案
        req.put("customs_platform_name","沈阳一链金服网络科技有限公司"); // 不变 公司备案
        req.put("declarer","宿浩");
        req.put("declarer_id_card","210905200103040010");
        req.put("source_platform_no","24022215504829011067"); // 一致的单号
        req.put("amount_freight",10);
        req.put("amount_discount",0);
        req.put("amount_paid_in",43);
        req.put("pay_type",1);
        req.put("pay_no","24022215504829011067"); // 一致的单号
        req.put("create_time",System.currentTimeMillis()); // 十位时间戳
        req.put("pay_time",System.currentTimeMillis()); // 十位时间戳
//        req.put("order_goods.goods_spu","BS00000001");
//        req.put("order_goods.sku_id","138347597");
//        req.put("order_goods.goods_num",1);
//        req.put("order_goods.goods_price",97.00);

        HouniaoCheckDTO houniaoCheckDTO = new HouniaoCheckDTO();
        houniaoCheckDTO.setSku_id("135328826");
        houniaoCheckDTO.setGoods_num(1);
        houniaoCheckDTO.setGoods_spu("BS00015308");
        houniaoCheckDTO.setGoods_price("1.00");

        JSONObject jss = JSON.parseObject(JSONObject.toJSONString(houniaoCheckDTO));
        jss = houniaoApiUtil.sortJsonObject(jss);

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jss);
        req.put("order_goods",jsonArray);
//        req.put("sign","8920d8a158daa660004a4336089f8098");

        JSONObject js = houniaoApiUtil.client(req, HouniaoConstant.ORDER_BUYNOW.getUrl());
        System.out.println(js);
        return R.ok().put("data",js);
    }

    @GetMapping("/howManyBaoShui")
    public R howManyBaoShui(){
        JSONObject req = new JSONObject();
        req.put("current_page", 1);
        req.put("page_size", 50);
        req.put("offset", 0);
        req.put("trade_type_id", 1);
        JSONObject js = houniaoApiUtil.client(req, HouniaoConstant.GOODS_GET_LIST.getUrl());
        return R.ok().put("data",js);
    }

    @GetMapping("/searchGoods/{goods_spu}")
    public R searchGoods(@PathVariable("goods_spu") String goods_spu){
        JSONObject req = new JSONObject();
        req.put("goods_spu", goods_spu);
        JSONObject js = houniaoApiUtil.client(req, HouniaoConstant.GOODS_SPEC_PRICE.getUrl());
        return R.ok().put("data",js);
    }

    //清理订单未发放奖励数据
    @GetMapping("/clearOrderGainsData")
    public R clearOrderGainsData(){
        String ipAddress = "";
        try{
            InetAddress inetAddress = InetAddress.getLocalHost();
            // 获取IP地址字符串
            ipAddress = inetAddress.getHostAddress();
            System.out.println("IP Address: " + ipAddress);
        }catch(Exception e){
            e.printStackTrace();
        }
        shopOrderGainsService.clearOrderGainsData();
        return R.ok(ipAddress);
    }

    /*
        用户现在的等级，距离升级所差的
     */
    @GetMapping("/getGrade")
    public R getGrade(@RequestParam("userId") Long userId) {

        PointGradeConfigDTO config = pointGradeConfigService.info();

        //判定店长的条件  是否大于10000了
        BigDecimal totalPrice = childOrderService.getObtainActivationTotalPrice(userId);

        //激活人数是否够
        Integer allActivatingCount = accountService.getAllActivatingCount(userId);

        //还差多少激活人数
        Integer activatingCount = (config.getGeNumPeople() - allActivatingCount) > 0 ? config.getGeNumPeople() - allActivatingCount : 0;

        //直推人数
        Integer childActivatingCount = accountService.getChildActivatingCount(userId);
        //还差多少直推人数
        Integer childActivatingCountDifference = (config.getNumDirectReferrals() - childActivatingCount) > 0 ? (config.getNumDirectReferrals() - childActivatingCount) : 0;

        //

        HashMap<Object,String> map = new HashMap<>();

        map.put("totalPrice",totalPrice.toString());//一共消费
        map.put("activatingCount",activatingCount.toString());//还差多少激活人数
        map.put("childActivatingCountDifference",childActivatingCountDifference.toString()); //还差多少直推人数
        map.put("childActivatingCount",allActivatingCount.toString());//已激活人数
        map.put("storeManager","10000");
        map.put("cloudShopkeeper","30000");
        map.put("totalPeople",config.getGeNumPeople().toString());//共需要多少激活人

        return R.ok().put("data",map);
    }


    /**
     * 快钱H5支付测试
     */

    @GetMapping("/testH5Pay")
    public R testKuaiqian(){
        Map<String, Object> request = new TreeMap<String, Object>();
//        Map<String, Object> requestMap = new TreeMap<String, Object>();

        String string = "";
        request.put("inputCharset",1);
        request.put("bgUrl","https://xhxzy.zhongyihuixuan.com");
        request.put("version","mobile1.0");
        request.put("language",1);
        request.put("signType",4);
        request.put("merchantAcctId","81231005399144001");    //快钱分给商户的11位商户编号。传值为商户号后面加01
        request.put("orderId","202407231721704537");
        request.put("orderAmount",10);
        request.put("orderTime","20240723111537");
        request.put("productName","testgoods");
        request.put("payType",21);
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (String key : request.keySet()) {
            sb.append(key);
            sb.append("={");
            sb.append(request.get(key));
            sb.append("}");
            if (i < request.size() - 1) {
                sb.append("&");
            }
            i++;
        }
//        System.out.println(sb);
        request.put("signMsg",sb);
        request.put("terminalIp","127.0.0.1");
        request.put("tdpformName","ceshi");





        System.out.println("请求参数:" + JSON.toJSONString(request));

        //提交地址
//		String reqUrl ="https://sandbox.99bill.com/sdk-gateway/sdkGatewayService";
        String reqUrl = "https://sandbox.99bill.com/mobilegateway/recvMerchantInfoAction.htm"; //生产地址



        String response = "";

        try {

            response = HttpUtil.doPostJsonRequest(JSON.toJSONString(request), reqUrl, 3000, 8000);

            //JDK1.8  用LinkedHashMap，两个方法二选一
            //方法一
            Map<String, Object> m = JSON.parseObject(response, LinkedHashMap.class, Feature.OrderedField);
            //方法二
            //Map<String,Object> m = new HashMap<String, Object>();
            //m = JSON.parseObject(response, LinkedHashMap.class, Feature.OrderedField);

            //JDK1.8  如果用该方法，验签的mpayInfo顺序错误，会导致验签失败
            //Map<String,Object> m = new HashMap<String, Object>();
            //m = JSON.parseObject(response, Map.class);

			System.out.println("m==="+m);
            System.out.println("response==="+response);
//            return response;


        } catch (Exception e) {
            e.printStackTrace();
//            return "";
        }
        return R.ok();
    }








}
